import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Card, Table, Form, Button, Input, Select, Upload, message, Modal } from 'antd';
import { history } from 'umi'
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import {
    fetchPostReference,
    downTemplatePositionMapping,
    checkPositionMappingBeforeUpload
} from '@/services/setting/salaryReference';
import { download } from '@/utils/utils';
import { dictionaryList } from '@/services/dictionary';
import { useTemplateInfo } from '@/pages/Setting/DataManagement/SalaryReference/hooks';

import groupBy from 'lodash/groupBy';
import cookie from 'js-cookie';
import xss from 'xss';
import authHelper from '@/utils/auth/helper';
import clone from 'lodash/clone';
import { Pagination } from '@/components';
import styles from '../SalaryReference/index.less';

const { Option } = Select;
const { checkCode } = authHelper;

const initPagination = {
    pageSize: 10,
    current: 1,
    total: 0
};
const View = props => {
    const { user, form } = props;
    const { getFieldDecorator } = form;
    const User = user.currentUser; // 当前登陆人
    const [data, setData] = React.useState('');
    const [pagination, setPagination] = React.useState(initPagination); // 页码
    const [dict, setDict] = React.useState([]);
    const [load, setLoad] = React.useState(false);

    const [templateLoading, templateInfo] = useTemplateInfo({ companyId: User.companyId, iconType: 'positionMapping' });

    const formatter = text => String(text ?? '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    // 表格列项
    const columns = [
        {
            title: '微微职位类别',
            dataIndex: 'firstPositionCodeName',
            render: (text, list) => {
                if (list.firstPositionCodeName && list.secondPositionCodeName) {
                    return `${list.firstPositionCodeName}-${list.secondPositionCodeName}`;
                }
                return '';
            }
        },
        {
            title: '微微职位名称',
            dataIndex: 'postName'
        },
        {
            title: '微微职级',
            dataIndex: 'gradeCode'
        },
        {
            title: '微微职位代码',
            // width: 220,
            dataIndex: 'postCode'
        },
        {
            title: '参考数据名称',
            // width: 220,
            dataIndex: 'salaryStandardName'
        },
        {
            title: '参考职位类别',
            // width: 220,
            dataIndex: 'postTypeName'
        },
        {
            title: '参考职位名称',
            // width: 120,
            dataIndex: 'refPostName'
        },
        {
            title: '参考职位代码',
            dataIndex: 'refSalaryPostCode'
        },
        {
            title: '一线城市90分位',
            dataIndex: 'firstLineNineQuantile',
            formatter
        },
        {
            title: '一线城市75分位',
            dataIndex: 'firstLineSevenQuantile',
            render: formatter
        },
        {
            title: '一线城市50分位',
            dataIndex: 'firstLineFiveQuantile',
            render: formatter
        },
        {
            title: '一线城市25分位',
            dataIndex: 'firstLineTwoQuantile',
            render: formatter
        },
        {
            title: '二线城市90分位',
            dataIndex: 'secondLineNineQuantile',
            formatter
        },
        {
            title: '二线城市75分位',
            dataIndex: 'secondLineSevenQuantile',
            render: formatter
        },
        {
            title: '二线城市50分位',
            dataIndex: 'secondLineFiveQuantile',
            render: formatter
        },
        {
            title: '二线城市25分位',
            dataIndex: 'secondLineTwoQuantile',
            render: formatter
        }
    ];

    // 搜索条件
    const { postMappingFieldType } = groupBy(dict, 'code');
    const prefixSelector = getFieldDecorator('searchType', {
        initialValue: ''
    })(
        <Select style={{ width: 120 }}>
            {postMappingFieldType &&
                postMappingFieldType.map(item => <Option value={item.dictValue}>{item.dictName}</Option>)}
        </Select>
    );
    // 获取列表数据
    const fetchData = async reset => {
        const values = form.getFieldsValue();
        const payload = {
            companyId: User.companyId,
            departmentId: User.departmentId,
            employeeCode: User.employeeCode,
            pageNo: reset ? 1 : pagination.current,
            pageSize: reset ? 10 : pagination.pageSize,
            searchName: values.searchName || '',
            searchType: values.searchType || ''
        };
        setLoad(true);
        const response = await fetchPostReference(payload);
        if (response && response.code === 10000) {
            setData(response.data.rows);
            setPagination({
                ...pagination,
                total: response.data.total,
                pageSize: response.data.pageSize,
                current: response.data.pageNo
            });
        }
        setLoad(false);
    };

    // 下载模板
    const downloadTemp = async () => {
        const response = await downTemplatePositionMapping();
        download({
            getData: () => response
        });
    };
    // 导入数据
    const uploadExcel = v => {
        if (v.file.name.toLowerCase().indexOf('xlsx') > -1 || v.file.name.toLowerCase().indexOf('xls') > -1) {
            const formData = new FormData();
            formData.append('file', v.file);
            fetch('/api/oa/v1/stream/postmapping/importdata', {
                method: 'POST',
                headers: {
                    Authorization: cookie.get('Authorization')
                },
                body: formData
            })
                .then(response => response.json())
                .then(res => {
                    if (res && res.code === 10000) {
                        history.push({
                            pathname: '/personal/portal/flow/mine/list/apply',
                            query: {
                                templateId: templateInfo.id,
                                formDeploymentId: templateInfo.formDeploymentId,
                                processDeploymentId: templateInfo.processDeploymentId,
                                templateName: templateInfo.templateName,
                                version: res.data,
                                ftype: 'import'
                            },
                            state: { tabRoute: true }
                        });
                    } else {
                        Modal.error({
                            title: '导入失败',
                            okText: '知道了',
                            content: (
                                <div
                                    style={{ overflow: 'auto', maxHeight: 300, paddingRight: 15 }}
                                    dangerouslySetInnerHTML={{ __html: xss(res.msg) }}
                                ></div>
                            )
                        });
                    }
                });
        } else {
            message.error('您上传的文件格式不正确,请重新上传！');
        }
    };
    // 表单搜索
    const handleSearch = e => {
        e.preventDefault();
        fetchData(1);
    };

    // 获取字典
    const getDict = async () => {
        const result = await dictionaryList({
            codes: ['postMappingFieldType']
        });
        if (result && result.code === 10000) {
            const newData = clone(result.data);
            newData.unshift({ code: 'postMappingFieldType', dictValue: '', dictName: '请选择' });
            setDict(newData);
        }
    };

    const changeTable = p => {
        setPagination({
            ...pagination,
            ...p
        });
    };
    useEffect(() => {
        getDict();
    }, []);
    useEffect(() => {
        fetchData();
    }, [pagination.pageSize, pagination.current]);

    /* 根据流程是否处于审批，判断是否能上传 */
    const [uploadDisabled, setUploadDisabled] = React.useState(false);
    const checkUpload = async () => {
        const res = await checkPositionMappingBeforeUpload({ formKey: 'positionMapping' });
        setUploadDisabled(!res.data);
    };
    React.useEffect(() => {
        checkUpload();
    }, []);
    const handleUpload = () => {
        if (uploadDisabled) {
            message.warn('当前有数据变更申请在进行中，请先完成相关审批！');
        }
    };

    return (
        <PageHeaderWrapper>
            <Card bordered={false} title="职位映射">
                <div className={styles.flex}>
                    <Form layout="inline" onSubmit={handleSearch}>
                        <Form.Item>
                            {getFieldDecorator('searchName')(
                                <Input
                                    addonBefore={prefixSelector}
                                    style={{ width: '100%' }}
                                    placeholder="请输入关键词"
                                />
                            )}
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                搜索
                            </Button>
                        </Form.Item>
                    </Form>
                    <div>
                        {checkCode('system:data:post:download') ? (
                            <Button
                                type="primary"
                                onClick={() => {
                                    downloadTemp();
                                }}
                            >
                                导出数据
                            </Button>
                        ) : (
                            ''
                        )}
                        {checkCode('system:data:post:upload') ? (
                            <Upload disabled={uploadDisabled} customRequest={uploadExcel} showUploadList={false}>
                                <Button
                                    disabled={templateLoading}
                                    loading={templateLoading}
                                    onClick={handleUpload}
                                    type="primary"
                                    ghost
                                    style={{ marginLeft: 15 }}
                                >
                                    导入数据
                                </Button>
                            </Upload>
                        ) : (
                            ''
                        )}
                        <Button
                            type="primary"
                            ghost
                            onClick={() => {
                                history.push({
                                    pathname:
                                        '/office/personnelManagement/organization/dataManagement/postReference/history'
                                });
                            }}
                            style={{ marginLeft: 15 }}
                        >
                            历史
                        </Button>
                    </div>
                </div>
                <Table
                    loading={load}
                    dataSource={data}
                    columns={columns}
                    scroll={{
                        x: 'max-content'
                    }}
                    pagination={false}
                />
                <Pagination loading={load} onChange={changeTable} {...pagination} />
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ loading, user }) => ({
        user,
        loading
    }))(Form.create()(View))
);
